<template>
  <div>
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="phone"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不正确'
          }
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        required
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          {
            pattern: /\d{6}/,
            message: '验证码格式不正确'
          }
        ]"
      >
        <template #button>
          <van-button size="small" type="primary">发送验证码</van-button>
        </template>
      </van-field>
      <div >
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          :disabled="isLoading"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  name: 'login',
  data () {
    return {
      phone: '13268920665',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    onSubmit (values) {
      console.log('submit', values)
      this.isLoading = true
      // 发送登录请求
      userLogin(values)
        .then(res => {
          console.log(res)
          this.$toast.success('登陆成功')
          // 获取登陆成功令牌
          setToken(res.data.data)
          // 登陆成功跳转到首页
          this.$router.push({ path: '/' })
        })
        .catch(err => {
          console.log(err)
          this.$toast.fail('账号或验证码错误')
        })
        .then(() => {
          // 最后一个then，只要本次请求完后就会执行，不管成功还是失败
          this.isLoading = false
        })
    }
  }
}
</script>

<style lang="less">
.van-nav-bar__content {
  background-color: white
  ;
  .van-nav-bar__left {
    .van-nav-bar__arrow {
      color: black;
    }
    .van-nav-bar__text {
      color: black;
    }
  }

  .van-nav-bar__title {
    color: black;
  }
}
</style>
